<template>
  <div class="role-container">
    <div class="page-header">
      <h2>角色管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增角色
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" label="#" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色编码" min-width="120" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="primary" link @click="handlePermission(scope.row)">
              <el-icon><Setting /></el-icon>权限设置
            </el-button>
            <el-button
              type="primary"
              link
              :disabled="scope.row.code === 'ADMIN'"
              @click="handleToggleStatus(scope.row)"
            >
              <el-icon><CircleCheck v-if="scope.row.status === 0" /><CircleClose v-else /></el-icon>
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-button>
            <el-button
              type="primary"
              link
              :disabled="scope.row.code === 'ADMIN'"
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色编码" 
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入角色描述" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
      destroy-on-close
    >
      <div v-if="currentRole" class="permission-header">
        <h3>{{ currentRole.name }}</h3>
        <p>{{ currentRole.description }}</p>
      </div>
      
      <el-tabs v-model="activePermissionTab">
        <el-tab-pane label="菜单权限" name="menu">
          <div class="menu-permission-container">
            <!-- 遍历每个主菜单 -->
            <div v-for="menu in menuTree" :key="menu.id" class="menu-section">
              <div class="menu-section-header">
                <el-checkbox 
                  v-model="menuCheckedMap[menu.id]" 
                  @change="(val) => handleParentMenuChange(menu.id, val)"
                >
                  {{ menu.title }}
                </el-checkbox>
              </div>
              <div class="menu-section-content">
                <el-row :gutter="10">
                  <el-col :span="8" v-for="(child, index) in menu.children" :key="child.id" class="menu-item">
                    <el-checkbox 
                      v-model="menuCheckedMap[child.id]"
                      @change="(val) => handleChildMenuChange(menu.id, child.id, val)"
                    >
                      {{ child.title }}
                    </el-checkbox>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据权限" name="data">
          <el-form label-width="120px">
            <el-form-item label="数据权限范围">
              <el-radio-group v-model="dataPermission.scope">
                <el-radio :label="1">全部数据权限</el-radio>
                <el-radio :label="2">本部门及以下数据权限</el-radio>
                <el-radio :label="3">本部门数据权限</el-radio>
                <el-radio :label="4">仅本人数据权限</el-radio>
                <el-radio :label="5">自定义数据权限</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="自定义部门" v-if="dataPermission.scope === 5">
              <el-tree-select
                v-model="dataPermission.departments"
                :data="departmentOptions"
                :props="{ children: 'children', label: 'name' }"
                show-checkbox
                multiple
                node-key="id"
                default-expand-all
                placeholder="请选择部门"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Refresh, 
  Edit, 
  Delete, 
  Setting, 
  CircleCheck, 
  CircleClose 
} from '@element-plus/icons-vue'

// 表单引用
const roleFormRef = ref(null)
const menuTreeRef = ref(null)

// 表格加载状态
const tableLoading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const permissionDialogVisible = ref(false)
const activePermissionTab = ref('menu')
const currentRole = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 角色表单
const roleForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 1
})

// 数据权限
const dataPermission = reactive({
  scope: 1,
  departments: []
})

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'ADMIN',
    description: '系统超级管理员，拥有所有权限',
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 2,
    name: '调度员',
    code: 'DISPATCHER',
    description: '负责车辆调度和运输计划管理',
    status: 1,
    createTime: '2025-01-02 00:00:00'
  },
  {
    id: 3,
    name: '财务人员',
    code: 'FINANCE',
    description: '负责财务管理和结算',
    status: 1,
    createTime: '2025-01-03 00:00:00'
  },
  {
    id: 4,
    name: '客服人员',
    code: 'CUSTOMER_SERVICE',
    description: '负责客户服务和投诉处理',
    status: 1,
    createTime: '2025-01-04 00:00:00'
  },
  {
    id: 5,
    name: '普通用户',
    code: 'USER',
    description: '普通用户，拥有基本查看权限',
    status: 0,
    createTime: '2025-01-05 00:00:00'
  }
])

// 菜单树数据
const menuTree = ref([
  {
    id: 1,
    title: '仪表盘',
    path: '/',
    children: []
  },
  {
    id: 2,
    title: '基础数据',
    path: '/base-data',
    children: [
      { id: 21, title: '企业/承运商管理', path: '/base-data/enterprise' },
      { id: 22, title: '车辆档案', path: '/base-data/vehicle' },
      { id: 23, title: '驾驶员档案', path: '/base-data/driver' },
      { id: 24, title: '路线地图', path: '/base-data/route' },
      { id: 25, title: '计价模型', path: '/base-data/pricing' }
    ]
  },
  {
    id: 3,
    title: '订单管理',
    path: '/orders',
    children: [
      { id: 31, title: '订单列表', path: '/orders/list' },
      { id: 32, title: '创建订单', path: '/orders/create' },
      { id: 33, title: '紧急订单处理', path: '/orders/emergency' }
    ]
  },
  {
    id: 4,
    title: '运输计划',
    path: '/planning',
    children: [
      { id: 41, title: '路径优化', path: '/planning/route-optimization' },
      { id: 42, title: '装载优化', path: '/planning/load-optimization' }
    ]
  },
  {
    id: 5,
    title: '调度执行',
    path: '/dispatch',
    children: [
      { id: 51, title: '实时跟踪', path: '/dispatch/tracking' },
      { id: 52, title: '异常管理', path: '/dispatch/exceptions' }
    ]
  },
  {
    id: 6,
    title: '费用结算',
    path: '/billing',
    children: [
      { id: 61, title: '单据处理', path: '/billing/documents' },
      { id: 62, title: '会计处理', path: '/billing/accounting' }
    ]
  },
  {
    id: 7,
    title: '报表分析',
    path: '/reports',
    children: [
      { id: 71, title: 'KPI仪表盘', path: '/reports/kpi' },
      { id: 72, title: '商业智能', path: '/reports/business-intelligence' }
    ]
  },
  {
    id: 8,
    title: '系统管理',
    path: '/system',
    children: [
      { id: 81, title: '用户管理', path: '/system/user' },
      { id: 82, title: '角色管理', path: '/system/role' },
      { id: 83, title: '部门管理', path: '/system/department' },
      { id: 84, title: '职位管理', path: '/system/position' },
      { id: 85, title: '菜单管理', path: '/system/menu' },
      { id: 86, title: '系统日志', path: '/system/log' }
    ]
  }
])

// 部门选项
const departmentOptions = ref([
  {
    id: 1,
    name: '总公司',
    children: [
      {
        id: 2,
        name: '信息技术部'
      },
      {
        id: 3,
        name: '运输部',
        children: [
          {
            id: 6,
            name: '调度组'
          },
          {
            id: 7,
            name: '车队管理组'
          }
        ]
      },
      {
        id: 4,
        name: '财务部'
      },
      {
        id: 5,
        name: '客服部'
      }
    ]
  }
])

// 菜单选中状态映射
const menuCheckedMap = reactive({})

// 加载角色列表
const loadRoleList = async () => {
  tableLoading.value = true
  try {
    // 实际项目中应该调用API获取角色列表
    // const { data } = await getRoleList({
    //   ...searchForm,
    //   page: pagination.currentPage,
    //   pageSize: pagination.pageSize
    // })
    // tableData.value = data.list
    // pagination.total = data.total
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用模拟数据
    pagination.total = tableData.value.length
    
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadRoleList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadRoleList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadRoleList()
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  resetRoleForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetRoleForm()
  
  // 填充表单数据
  roleForm.id = row.id
  roleForm.name = row.name
  roleForm.code = row.code
  roleForm.description = row.description
  roleForm.status = row.status
  
  dialogVisible.value = true
}

// 权限设置
const handlePermission = (row) => {
  currentRole.value = row
  
  // 先设置数据权限
  if (row.code === 'ADMIN') {
    // 超级管理员拥有所有权限
    dataPermission.scope = 1
    dataPermission.departments = []
  } else if (row.code === 'DISPATCHER') {
    // 调度员拥有部分权限
    dataPermission.scope = 2
    dataPermission.departments = []
  } else {
    // 其他角色拥有有限权限
    dataPermission.scope = 4
    dataPermission.departments = []
  }
  
  // 初始化菜单选中状态
  initMenuCheckedMap()
  
  // 显示对话框
  permissionDialogVisible.value = true
  
  // 在对话框显示后，等待DOM更新完成再设置菜单选中状态
  nextTick(() => {
    if (row.code === 'ADMIN') {
      // 超级管理员拥有所有权限
      const allMenuIds = getAllMenuIds(menuTree.value)
      setCheckedMenuIds(allMenuIds)
    } else if (row.code === 'DISPATCHER') {
      // 调度员拥有部分权限
      setCheckedMenuIds([1, 3, 31, 32, 33, 4, 41, 42, 5, 51, 52])
    } else {
      // 其他角色拥有有限权限
      setCheckedMenuIds([1])
    }
  })
}

// 获取所有菜单ID
const getAllMenuIds = (menus) => {
  const ids = []
  const traverse = (items) => {
    items.forEach(item => {
      ids.push(item.id)
      if (item.children && item.children.length > 0) {
        traverse(item.children)
      }
    })
  }
  traverse(menus)
  return ids
}

// 初始化菜单选中状态
const initMenuCheckedMap = () => {
  // 清空之前的选中状态
  Object.keys(menuCheckedMap).forEach(key => {
    delete menuCheckedMap[key]
  })
  
  // 为所有菜单项设置初始状态为false
  const initMenus = (menus) => {
    menus.forEach(menu => {
      menuCheckedMap[menu.id] = false
      if (menu.children && menu.children.length > 0) {
        initMenus(menu.children)
      }
    })
  }
  
  initMenus(menuTree.value)
}

// 处理父菜单选中状态变化
const handleParentMenuChange = (parentId, checked) => {
  // 找到对应的父菜单
  const parentMenu = menuTree.value.find(item => item.id === parentId)
  if (parentMenu && parentMenu.children) {
    // 将所有子菜单设置为相同的选中状态
    parentMenu.children.forEach(child => {
      menuCheckedMap[child.id] = checked
    })
  }
}

// 处理子菜单选中状态变化
const handleChildMenuChange = (parentId, childId, checked) => {
  // 检查父菜单下的所有子菜单是否都被选中
  const parentMenu = menuTree.value.find(item => item.id === parentId)
  if (parentMenu && parentMenu.children) {
    const allChildrenChecked = parentMenu.children.every(child => menuCheckedMap[child.id])
    const anyChildChecked = parentMenu.children.some(child => menuCheckedMap[child.id])
    
    // 更新父菜单的选中状态
    menuCheckedMap[parentId] = allChildrenChecked
  }
}

// 获取所有选中的菜单ID
const getCheckedMenuIds = () => {
  return Object.entries(menuCheckedMap)
    .filter(([_, checked]) => checked)
    .map(([id]) => parseInt(id))
}

// 设置选中的菜单ID
const setCheckedMenuIds = (menuIds) => {
  // 先初始化所有菜单为未选中状态
  initMenuCheckedMap()
  
  // 设置指定的菜单为选中状态
  menuIds.forEach(id => {
    menuCheckedMap[id] = true
  })
}

// 保存权限设置
const savePermissions = async () => {
  try {
    const menuIds = getCheckedMenuIds()
    
    // 实际项目中应该调用API保存角色权限
    // await saveRolePermissions({
    //   roleId: currentRole.value.id,
    //   menuIds: menuIds,
    //   dataScope: dataPermission.scope,
    //   departmentIds: dataPermission.scope === 5 ? dataPermission.departments : []
    // })
    
    ElMessage.success('保存权限成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

// 启用/禁用角色
const handleToggleStatus = (row) => {
  if (row.code === 'ADMIN') {
    ElMessage.warning('超级管理员角色不允许禁用')
    return
  }
  
  const action = row.status === 1 ? '禁用' : '启用'
  const newStatus = row.status === 1 ? 0 : 1
  
  ElMessageBox.confirm(
    `确定要${action}角色 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API更新角色状态
        // await updateRoleStatus({
        //   roleId: row.id,
        //   status: newStatus
        // })
        
        // 更新本地数据
        row.status = newStatus
        
        ElMessage.success(`${action}角色成功`)
      } catch (error) {
        console.error(`${action}角色失败:`, error)
        ElMessage.error(`${action}角色失败`)
      }
    })
    .catch(() => {})
}

// 删除角色
const handleDelete = (row) => {
  if (row.code === 'ADMIN') {
    ElMessage.warning('超级管理员角色不允许删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除角色 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API删除角色
        // await deleteRole(row.id)
        
        // 更新本地数据
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          pagination.total--
        }
        
        ElMessage.success('删除角色成功')
      } catch (error) {
        console.error('删除角色失败:', error)
        ElMessage.error('删除角色失败')
      }
    })
    .catch(() => {})
}

// 重置角色表单
const resetRoleForm = () => {
  Object.keys(roleForm).forEach(key => {
    if (key === 'status') {
      roleForm[key] = 1
    } else {
      roleForm[key] = ''
    }
  })
  
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 实际项目中应该调用API添加角色
          // const { data } = await addRole(roleForm)
          
          // 模拟添加角色
          const newRole = {
            id: Date.now(),
            name: roleForm.name,
            code: roleForm.code,
            description: roleForm.description,
            status: roleForm.status,
            createTime: new Date().toLocaleString()
          }
          
          tableData.value.push(newRole)
          pagination.total++
          
          ElMessage.success('添加角色成功')
        } else {
          // 实际项目中应该调用API更新角色
          // await updateRole(roleForm)
          
          // 更新本地数据
          const index = tableData.value.findIndex(item => item.id === roleForm.id)
          if (index !== -1) {
            tableData.value[index] = {
              ...tableData.value[index],
              name: roleForm.name,
              description: roleForm.description,
              status: roleForm.status
            }
          }
          
          ElMessage.success('更新角色成功')
        }
        
        dialogVisible.value = false
      } catch (error) {
        console.error('保存角色失败:', error)
        ElMessage.error('保存角色失败')
      }
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoleList()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.permission-header h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.permission-header p {
  margin: 0;
  color: #909399;
}

.menu-permission-container {
  max-height: 500px;
  overflow-y: auto;
}

.menu-section {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.menu-section-header {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.menu-section-content {
  padding: 10px 15px;
}

.menu-item {
  margin-bottom: 8px;
}
</style>
